clear
set graphics off
set seed [withheld]

*iterations
local RR=${masteriter}
local thresh=${masterthresh}
local agegroup "${agegroup}"
local sample "${sample}"
local n_prod_vars=1
		
	quietly use "${data}/data_`agegroup'.dta", clear
	quietly bys S J: gen cellcount=_N
	keep if cellcount>=`thresh'

local full_sample_obs = r(N)


quietly ren (  tfpvar) (lprod_1  )

local use_sample_obs = r(N)

tempfile AA BB
quietly save `AA'

* Conditional order of plants 
bys  T J (order) : gen cond_order = _n
quietly keep  S T J cond_order
*Here we are saving an ordered list of plants' locations within each industry.
*We will permute the order of the dataset then re-match to this ordered list
*in order to generate permuted locations with the same industry profile.
quietly save `BB'

forvalues rr=0(1)`RR' {

*Zero Iteration is True Values
if `rr'==0 {
	* Loop through the productivity measures
	forvalues nn=1(1)`n_prod_vars' {
		tempfile C`nn' D`nn'
	}
	forvalues nn=1(1)`n_prod_vars' {
		use `AA', clear
		run "${code}/Permute_worker.do" `nn'
		quietly save `D`nn''
		quietly use `D`nn'', replace
		quietly keep if _n==1 
		quietly keep  var* 
		quietly save `C`nn''
	}

	* Merge the files
	use `C1',clear
	quietly cap drop _m
	
	forvalues nn=1(1)`n_prod_vars' {
		quietly merge 1:1 _n using `C`nn'', nogen
		}
	quietly gen iter	= `rr'
	 save "${results}/temp/thresh_`thresh'_permute_out_stats_`sample'_${date}.dta", replace

} 
else {
/*
Positive Iterations Use Randomized Location
*/
	use `AA', clear
	quietly gen randu = runiform()
	quietly bys  T J (randu) : gen cond_order = _n
	quietly ren S true_location
	quietly merge 1:1  T J cond_order using `BB'
	tempfile AB
	quietly save `AB'

	forvalues nn=1(1)`n_prod_vars' {
		tempfile C`nn' D`nn'
		}
	forvalues nn=1(1)`n_prod_vars' {
		use `AB', clear
		run "${code}/Permute_worker.do" `nn'
		quietly save `D`nn''	
		quietly use `D`nn'', replace
		quietly keep if _n==1 
		quietly keep var* 
		quietly save `C`nn''
	}

	* Merge the files
	use `C1',clear
	quietly cap drop _m
	forvalues nn=1(1)`n_prod_vars' {
		quietly merge 1:1 _n using `C`nn'', nogen
	}
	
	quietly gen iter	= `rr'
	
	quietly  append using "${results}/temp/thresh_`thresh'_permute_out_stats_`sample'_${date}.dta"
	quietly  save "${results}/temp/thresh_`thresh'_permute_out_stats_`sample'_${date}.dta", replace
}
	if `rr'== 10 | `rr'==100 | `rr'==250 | `rr' == 500 | `rr'==750 | `rr'==900 {
		di "`rr'"
	}
}
di "`sample'"

forvalues ii=1/`n_prod_vars' {
foreach svar in capT tau {
	foreach var in var {
	use "${results}/temp/thresh_`thresh'_permute_out_stats_`sample'_${date}.dta", clear
	*get true value as local
	sort iter
	local trueval_`var'			=`var'_`svar'_`ii'[1]
	local truevalprint_`var' 	= string(`trueval_`var'', "%05.3f")
	*get mean value as local
	 qui sum `var'_`svar'_`ii' if iter!=0, d
	local meanval_`var'			=r(mean)
	local textcenter_`var'		=`trueval_`var''
	local meanvalprint_`var' 	= string(`meanval_`var'', "%05.3f")
	local meanvaltable_`var' 	= string(`meanval_`var'', "%09.4g")
	
	*get pval as local
	sort `var'_`svar'_`ii'
	local perm_lci_`var'=`var'_`svar'_`ii'[25]
	local perm_uci_`var'=`var'_`svar'_`ii'[975]
	local tableperm_lci_`var' 	= string(`perm_lci_`var'', "%09.4g")
	local tableperm_uci_`var' 	= string(`perm_uci_`var'', "%09.4g")

	tempvar pval_`var'
	gen `pval_`var''			=_n
	sort iter
	local tablepval_`var'		=(_N-`pval_`var''[1])/`RR'
	local pval_`var'			=`pval_`var''[1]

clear
set obs 1
local ltfpvar = "tfpvar"

quietly gen perm_`var'_`svar'_mean=`meanvaltable_`var''
quietly gen perm_`var'_`svar'_lci=`tableperm_lci_`var''
quietly gen perm_`var'_`svar'_uci=`tableperm_uci_`var''


quietly cap gen thresh = `thresh'

quietly gen sample="`sample'"
quietly gen tfpvar="`ltfpvar'"
merge 1:1  thresh sample using "${results}/temp/thresh_results${date}.dta", nogen
save "${results}/temp/thresh_results${date}.dta", replace


}
}
}


